import NavBar from '@/components/NavBar';
import { useEffect, useRef, useState } from 'react';
import { useDispatch } from 'react-redux';
import styles from './index.module.scss';
import { addComment } from '@/store/action/comment';
import { useAppSelector } from '@/store';
import { Toast } from 'antd-mobile'
type Props = {
  onClose: () => void;
};

export default function CommentInput({ onClose }: Props) {
  const { detail } = useAppSelector((state) => state.article);
  // 输入框内容
  const [value, setValue] = useState('');

  // 输入框引用
  const txtRef = useRef<HTMLTextAreaElement>(null);

  useEffect(() => {
    // 输入框自动聚焦
    setTimeout(() => {
      txtRef.current!.focus();
    }, 100);
  }, []);

  const dispatch = useDispatch();
  // 发表评论
  const onSendComment = async () => {
    if (!value) return;
    // 发送请求，添加评论
    await dispatch(addComment({ target: detail.art_id, content: value }));
    onClose();
    Toast.show({ content: '评论成功' })
  };

  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar
        onBack={onClose}
        right={
          <span className="publish" onClick={onSendComment}>
            发表
          </span>
        }
        title={'评论文章'}
      ></NavBar>

      <div className="input-area">
        {/* 评论内容输入框 */}
        <textarea
          ref={txtRef}
          placeholder="说点什么~"
          rows={10}
          value={value}
          onChange={(e) => setValue(e.target.value.trim())}
        />
      </div>
    </div>
  );
}